package com.deer.wms.ware.task.web;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.model.Pack.PackDetail;
import com.deer.wms.base.system.model.SeedingCell;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.base.system.service.PackDetailService;
import com.deer.wms.base.system.service.SeedingCellService;
import com.deer.wms.busine.tactic.model.PrintTempInfo;
import com.deer.wms.busine.tactic.service.PrintTempInfoService;
import com.deer.wms.busine.tactic.service.PrintTempUtils;
import com.deer.wms.file.configurer.FileSetting;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.kuaidiniao.model.*;
import com.deer.wms.kuaidiniao.service.KuaidiniaoService;
import com.deer.wms.kuaidiniao.service.PrintParamService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.core.service.QueryCriteria;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.project.root.util.ExcelUtils;
import com.deer.wms.project.root.util.StringUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.model.address.ReceivingAddress;
import com.deer.wms.system.manage.model.address.ShippingAddress;
import com.deer.wms.system.manage.model.address.ShippingAddressDto;
import com.deer.wms.system.manage.model.carrier.Carrier;
import com.deer.wms.system.manage.model.customer.Customer;
import com.deer.wms.system.manage.model.organization.Organization;
import com.deer.wms.system.manage.model.ware.WareInfo;
import com.deer.wms.system.manage.service.*;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.model.SO.CreateSo.CreateSo;
import com.deer.wms.ware.task.model.SO.*;
import com.deer.wms.ware.task.model.SO.vo.SoDetailVo;
import com.deer.wms.ware.task.model.SO.vo.SoMasterVo;
import com.deer.wms.ware.task.model.Wave.WaveMaster;
import com.deer.wms.ware.task.service.SoDetailService;
import com.deer.wms.ware.task.service.SoMasterService;
import com.deer.wms.ware.task.service.WaveMasterService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jxl.format.CellFormat;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author guo
 * @since 2020/02/02
 */
@Api(description = "SO信息api接口")
@RestController
@RequestMapping("/so/masters")
public class SoMasterController {

    private Lock lock = new ReentrantLock();    //注意这个地方


    @Autowired
    private SoMasterService soMasterService;

    @Autowired
    private SoDetailService soDetailService;

    @Autowired
    private ValidatorService validatorService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CarrierService carrierService;

    @Autowired
    private WareInfoService wareInfoService;

    @Autowired
    private ReceivingAddressService receivingAddressService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Autowired
    private PackDetailService packDetailService;

    @Autowired
    private FileSetting fileSetting;

    @Autowired
    private KuaidiniaoService kuaidiniaoService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PrintParamService printParamService;

    @Autowired
    private ShippingAddressService shippingAddressService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private BillRecordService billRecordService;

    @Autowired
    private SeedingCellService seedingCellService;

    @Autowired
    private WaveMasterService waveMasterService;

    @ApiOperation(value = "ERP--》WMS生成出库单", notes = "ERP--》WMS生成出库单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/createSO")
    public Result createSO(@RequestBody CreateSo createSo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        if (true) {throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "xx");}
        soMasterService.createSO(createSo, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "新增SO信息", notes = "新增SO信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/insert")
    public Result add(@RequestBody SoData soData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        soMasterService.createSoMaster(soData, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/delete")
    public Result delete(Integer id) {
        soMasterService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "设置优先级", notes = "设置优先级")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @GetMapping("/priority")
    public Result setPriority(Integer soMasterId, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        if (lock.tryLock()) {
            try {
                Integer priority = soMasterService.getMaxPriority();
                priority = priority + 1;
                soMasterService.updatePriority(soMasterId, priority);
            } catch (Exception e) {
                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "设置优先级失败");
            } finally {
                lock.unlock();
            }
        } else {
            ResultGenerator.genSuccessResult("请重试");
        }
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "审核", notes = "审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @GetMapping("/review")
    public Result review(String billNo, Integer reviewResult, Integer caseDetailId, String memo, @ApiIgnore @User CurrentUser currentUser) {
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
        //-1不通过   0-流转中  1-通过  2-初始化
        Integer lastReviewResult = caseMasterService.review(caseDetailId, currentUser.getUserId(), reviewResult, memo);


        if (lastReviewResult == -1) {
            soMaster.setState(-1);
            soMasterService.updateById(soMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo, 24);//SO审核
            billRecord.setResult("退回");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        } else if (lastReviewResult == 0) {
            soMaster.setState(0);
            soMasterService.updateById(soMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo, 24);//SO审核
            billRecord.setResult("流转");
            billRecordService.updateById(billRecord);
        } else if (lastReviewResult == 2) {
            soMaster.setState(2);
            soMasterService.updateById(soMaster);
        } else if (lastReviewResult == 1) {
            soMaster.setState(1);
            soMasterService.updateById(soMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo, 24);//SO审核
            billRecord.setResult("通过");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        }
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "重新发起审核", notes = "重新发起审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @GetMapping("/reReview")
    public Result reReview(String billNo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);

        //初始化状态 2
        soMaster.setState(2);
        soMasterService.updateById(soMaster);
        caseMasterService.createCase(billNo, 2, currentUser.getUserId(), soMaster.getWareId(), soMaster.getOrganizationId());

        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "增删soMaster、soDetail", notes = "增删soMaster、soDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/update")
    public Result update(@RequestBody SoData soData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        BillRecord billRecord = new BillRecord();
        billRecord.setBillNo(soData.getSoMaster().getBillNo());
        billRecord.setRecordType(27);//SO修改
        billRecord.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord.setCreateUserId(currentUser.getUserId());
        billRecord.setCreateUserName(currentUser.getUserName());
        billRecordService.createBillRecord(billRecord, currentUser);
        SoMaster soMaster = soData.getSoMaster();
        soMasterService.updateById(soMaster);

        List<SoDetail> soDetails = soData.getSoDetails();

        for (int i = 0; i < soDetails.size(); i++) {
            SoDetail soDetail = soDetails.get(i);
            String detailNo = soData.getSoMaster().getBillNo() + "-" + (i + 1);
            soDetail.setDetailNo(detailNo);
            soDetail.setBillNo(soData.getSoMaster().getBillNo());
            soDetail.setDetailNo(detailNo);

            soDetailService.updateById(soDetail);
        }
        BillRecord billRecord1 = billRecordService.findByBillNoAndType(soData.getSoMaster().getBillNo(), 27);//SO修改
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord1.setModifyUserId(currentUser.getUserId());
        billRecord1.setModifyUserName(currentUser.getUserName());
        billRecordService.updateById(billRecord1);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        SoMaster soMaster = soMasterService.getById(id);
        return ResultGenerator.genSuccessResult(soMaster);
    }

    @GetMapping("/findByBillNo")
    public Result findByBillNo(@RequestParam String billNo) {
        SoMaster soMaster = soMasterService.getOneByField("bill_no", billNo);
        return ResultGenerator.genSuccessResult(soMaster);
    }

    @GetMapping("/list")
    public Result list(SoMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<SoMasterDto> list = soMasterService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "SO单整单复核")
    @GetMapping("/check")
    public Result check(String billNo, @ApiIgnore @User CurrentUser currentUser) {
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
        soMaster.setCheckTime(DateUtils.getNowDateTimeString());
        soMaster.setCheckUserId(currentUser.getUserId());
        soMaster.setCheckUserName(currentUser.getUserName());
        soMaster.setState(WareTaskConstant.SO_STATE_CHECKED);
        soMasterService.updateById(soMaster);
        List<SoDetail> list = soDetailService.findByBillNo(billNo);
        for (SoDetail detail : list
        ) {
            detail.setCheckQuantity(detail.getOrderQuantity());
            soDetailService.updateById(detail);
        }

        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/seedingCheck")
    public Result seedingCheck(String cellCode, String billNo, @ApiIgnore @User CurrentUser currentUser) {
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
        if (WareTaskConstant.SO_STATE_CHECKED.equals(soMaster.getState())) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该订单已经播种！");
        }
        soMaster.setCheckTime(DateUtils.getNowDateTimeString());
        soMaster.setCheckUserId(currentUser.getUserId());
        soMaster.setCheckUserName(currentUser.getUserName());
        soMaster.setState(WareTaskConstant.SO_STATE_CHECKED);
        soMasterService.updateById(soMaster);

        List<SoDetail> list = soDetailService.findByBillNo(billNo);
        Double quantity = 0.0;
        for (SoDetail detail : list) {
            quantity += detail.getOrderQuantity();
            detail.setCheckQuantity(detail.getOrderQuantity());
            soDetailService.updateById(detail);
        }


        SeedingCell seedingCell = seedingCellService.findBy("seeding_cell_code", cellCode);
        seedingCell.setBillNo(billNo);
        seedingCell.setState(1);
        seedingCellService.updateById(seedingCell);

        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/downSeeding")
    public Result downSeeding(String data, @ApiIgnore @User CurrentUser currentUser) {

        SeedingCell seedingCell = seedingCellService.findBy("seeding_cell_code", data);
        if (seedingCell == null) {
            SoMaster soMaster = soMasterService.findBy("ship_bill_code", data);
            if (soMaster != null) {
                seedingCell = seedingCellService.findBy("bill_no", soMaster.getBillNo());
            }
        }
        if (seedingCell != null) {
            seedingCell.setBillNo("");
            seedingCell.setState(-1);
            seedingCell.setQuantity(0.0);
            seedingCellService.updateById(seedingCell);
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/findByWaveCode")
    public Result findByWaveCode(Integer id, Integer wareId) {
        WaveMaster waveMaster = waveMasterService.getById(id);
        Integer waveId = null;
        if (waveMaster != null) {
            waveId = waveMaster.getWaveId();
        }
        List<SoMasterDto> list = soMasterService.findByWaveId(waveId, wareId);
        return ResultGenerator.genSuccessResult(list);
    }

    @PostMapping("/cancel")
    public Result cancel(String billNo) {
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
        soMaster.setState(WareTaskConstant.SO_STATE_CANCELED);
        soMasterService.updateById(soMaster);
        // List<SoMasterDto> list = soMasterService.findByWaveId(id);
        return ResultGenerator.genSuccessResult();
    }

    @ApiOperation(value = "合并SO信息", notes = "老产品设计，逻辑待研究")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/merge")
    public Result merge(@RequestBody Merge merge, @ApiIgnore @User CurrentUser currentUser) throws ParseException {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        String tableName = "so_master";
        Integer nextId = validatorService.getNextId(tableName);
        String billNo1 = "HB" + "-" + nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();
        //添加ASN单跟踪信息
        BillRecord billRecord = new BillRecord();
        billRecord.setBillNo(billNo1);
        billRecord.setRecordType(28);//SO合并
        billRecord.setCreateTime(createTime);
        billRecord.setCreateUserId(createUserId);
        billRecord.setCreateUserName(createUserName);
        billRecordService.createBillRecord(billRecord, currentUser);

        SoMasterCriteria criteria = new SoMasterCriteria();
        criteria.setBillNos(merge.getBillNos());
        List<SoMasterDto> soMasters = soMasterService.findList(criteria);
        SoMaster soMaster2 = new SoMaster();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date d4 = dateFormat.parse(DateUtils.getNowDateTimeString());
        Date d5 = dateFormat.parse(DateUtils.getNowDateTimeString());
        Date d6 = dateFormat.parse(DateUtils.getNowDateTimeString());


        for (int i = 0; i < soMasters.size(); i++) {
            SoMaster soMaster1 = soMasters.get(i);

            String deliveryTime = soMaster1.getDeliveryTime();
            String expectTimeFm = soMaster1.getExpectTimeFm();
            String expectTimeTo = soMaster1.getExpectTimeTo();

            if (i == 0) {
                d4 = dateFormat.parse(deliveryTime);
                d5 = dateFormat.parse(expectTimeFm);
                d6 = dateFormat.parse(expectTimeTo);

                soMaster2.setDeliveryTime(deliveryTime);
                soMaster2.setExpectTimeFm(expectTimeFm);
                soMaster2.setExpectTimeTo(expectTimeTo);
            }

            Date d1 = dateFormat.parse(deliveryTime);
            Date d2 = dateFormat.parse(expectTimeFm);
            Date d3 = dateFormat.parse(expectTimeTo);

            if (d1.before(d4)) {
                soMaster2.setDeliveryTime(deliveryTime);
            }
            if (d2.before(d5)) {
                soMaster2.setExpectTimeFm(expectTimeFm);
            }
            if (d3.before(d6)) {
                soMaster2.setExpectTimeTo(expectTimeTo);
            }
            soMaster2.setWareId(soMaster1.getWareId());
            soMaster2.setWareName(soMaster1.getWareName());
            soMaster2.setOrganizationId(soMaster1.getOrganizationId());
            soMaster2.setOrganizationName(soMaster1.getOrganizationName());
            soMaster2.setCustomerId(soMaster1.getCustomerId());
            soMaster2.setCustomerName(soMaster1.getCustomerName());
            soMaster2.setCarrierId(soMaster1.getCarrierId());
            soMaster2.setCarrierName(soMaster1.getCarrierName());
            soMaster2.setCreateTime(DateUtils.getNowDateTimeString());
            soMaster2.setCreateUserId(currentUser.getUserId());
            soMaster2.setCreateUserName(currentUser.getUserName());
            soMaster2.setOrderNo(soMaster1.getOrderNo());
            soMaster2.setInsertType(soMaster1.getInsertType());
            soMaster2.setSoUdfHs1(soMaster1.getSoUdfHs1());
            soMaster2.setSoUdfHs2(soMaster1.getSoUdfHs2());
            soMaster2.setSoUdfHs3(soMaster1.getSoUdfHs3());
            soMaster2.setMemo(soMaster1.getMemo());
            soMaster2.setReceivingAddressId(soMaster1.getReceivingAddressId());
            soMaster2.setLinkMan(soMaster1.getLinkMan());
            soMaster2.setLinkPhone(soMaster1.getLinkPhone());
            soMaster2.setProvince(soMaster1.getProvince());
            soMaster2.setCity(soMaster1.getCity());
            soMaster2.setArea(soMaster1.getArea());
            soMaster2.setDetailAddress(soMaster1.getDetailAddress());
        }
        soMaster2.setState(0);
        soMaster2.setCaseState(2);
        soMaster2.setBillNo(billNo1);
        soMaster2.setBillSource(2);

        soMasterService.save(soMaster2);
        List<SoDetail> soDetailList = new ArrayList<>();
        for (int i = 0; i < merge.getBillNos().size(); i++) {
            String billNo = merge.getBillNos().get(i);
            SoDetailCriteria criteria1 = new SoDetailCriteria();
            criteria1.setBillNo(billNo);
            List<SoDetailDto> soDetails = soDetailService.findList(criteria1);


            for (int y = 0; y < soDetails.size(); y++) {
                SoDetail soDetail = soDetails.get(y);
                soDetailService.updateById(soDetail);
                soDetailList.add(soDetail);
            }
            SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
            soMaster.setState(11);
            soMaster.setMergeNo(billNo1);
            soMasterService.updateById(soMaster);
        }
        for (int x = 0; x < soDetailList.size(); x++) {
            SoDetail soDetail = soDetailList.get(x);
            soDetail.setSoDetailId(null);
            soDetail.setBillNo(billNo1);
            soDetail.setDetailNo(billNo1 + "-" + (x + 1));
            soDetailService.save(soDetail);
        }

        BillRecord billRecord1 = billRecordService.findByBillNoAndType(billNo1, 28);//SO合并
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord1.setModifyUserId(createUserId);
        billRecord1.setModifyUserName(createUserName);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "归档SO信息 传billNo", notes = "归档SO信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/file")
    public Result file(@RequestBody FileData fileData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        for (int i = 0; i < fileData.getBillNos().size(); i++) {
            String billNo = fileData.getBillNos().get(i);
            soMasterService.createFile(billNo, currentUser);
        }
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "SO单据导入", notes = "SO单据导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @Transactional
    @PostMapping("/importSoBills")
    public Result importSoBills(SoImport excel, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }

        jxl.Workbook billWorkbook = null;


        String msg = "Excel 内容有问题，无法导入！";

        try {
            billWorkbook = jxl.Workbook.getWorkbook(excel.getModel().getInputStream());
            jxl.Sheet billSheet = billWorkbook.getSheet(0);

            int rows = billSheet.getRows();

            SoMaster soMaster = new SoMaster();

            String tableName = "so_master";
            Integer nextId = validatorService.getNextId(tableName);
            soMaster.setSoMasterId(nextId);
            soMasterService.save(soMaster);
            String billNo = "SO" + "-" + soMaster.getSoMasterId();


            String wareName = ExcelUtils.getCellString(billSheet, 0, 2).trim();
            Integer wareId = null;
            WareInfo wareInfo = wareInfoService.getOneByField("ware_name", wareName);
//            WareInfo wareInfo = wareInfoService.findBy("ware_name", wareName);
            if (wareInfo != null) {
                wareId = wareInfo.getWareId();

            } else {
                msg = "仓库名称错误！" + wareName;
                throw new Exception();
            }

            String organizationName = ExcelUtils.getCellString(billSheet, 1, 2).trim();
            Integer organizationId = null;
            QueryWrapper<Organization> qw = new QueryWrapper<>();
            Organization organization = organizationService.getOne(qw.eq("organizationName", organizationName));
            if (organization != null) {
                organizationId = organization.getOrganizationId();

            } else {
                msg = "货主名称错误！" + organizationName;
                throw new Exception();
            }
            String customerName = ExcelUtils.getCellString(billSheet, 2, 2).trim();
            Integer customerId = null;
            Customer customer = customerService.findBy("customer_name", customerName);
            if (customer != null) {
                customerId = customer.getCustomerId();

            } else {
                msg = "客户名称错误！" + customerName;
                throw new Exception();
            }

            String carrierName = ExcelUtils.getCellString(billSheet, 3, 2).trim();
            Integer carrierId = null;
            Carrier carrier = carrierService.findBy("carrier_name", carrierName);
            if (carrier != null) {
                carrierId = carrier.getCarrierId();

            } else {
                msg = "承运方名称错误！" + carrierName;
                throw new Exception();
            }

            String linkName = ExcelUtils.getCellString(billSheet, 4, 2).trim();
            Integer receivingAddressId = null;
            ReceivingAddress receivingAddress = receivingAddressService.findBy("link_man", linkName);
            if (receivingAddress != null) {
                receivingAddressId = receivingAddress.getReceivingAddressId();

            } else {
                msg = "联系人错误！" + linkName;
                throw new Exception();
            }
            String deliveryTime = ExcelUtils.getCellString(billSheet, 5, 2).trim();
            String expectTimeFm = ExcelUtils.getCellString(billSheet, 6, 2).trim();
            String expectTimeTo = ExcelUtils.getCellString(billSheet, 7, 2).trim();
            Integer soType = ExcelUtils.getCellInteger(billSheet, 8, 2);
            String memo = ExcelUtils.getCellString(billSheet, 9, 2);
            String soUdfHs1 = ExcelUtils.getCellString(billSheet, 10, 2);
            String soUdfHs2 = ExcelUtils.getCellString(billSheet, 11, 2);
            String soUdfHs3 = ExcelUtils.getCellString(billSheet, 12, 2);
            soMaster.setWareId(wareId);
            soMaster.setWareName(wareName);
            soMaster.setOrganizationId(organizationId);
            soMaster.setOrganizationName(organizationName);
            soMaster.setCustomerId(customerId);
            soMaster.setCustomerName(customerName);
            soMaster.setCarrierId(carrierId);
            soMaster.setCarrierName(carrierName);
            soMaster.setReceivingAddressId(receivingAddressId);
            soMaster.setLinkMan(linkName);
            soMaster.setState(0);
            String time = DateUtils.getNowDateTimeString();
            soMaster.setCreateUserId(currentUser.getUserId());
            soMaster.setCreateUserName(currentUser.getUserName());
            soMaster.setCreateTime(time);
            soMaster.setDeliveryTime(deliveryTime);
            soMaster.setExpectTimeFm(expectTimeFm);
            soMaster.setExpectTimeTo(expectTimeTo);
            soMaster.setOrderNo(1);
            soMaster.setBillSource(3); //导入
            soMaster.setInsertType(excel.getInsertType());
            soMaster.setSoUdfHs1(soUdfHs1);
            soMaster.setSoUdfHs2(soUdfHs2);
            soMaster.setSoUdfHs3(soUdfHs3);
            soMaster.setSoType(soType);
            soMaster.setMemo(memo);

            Integer state = caseMasterService.createCase(billNo, 3, currentUser.getUserId(), wareId, organizationId);

            soMaster.setCaseState(state);


            soMasterService.updateById(soMaster);


            Integer rowCount = 0;
            for (int i = 6; i < rows; i++) {
                String content = ExcelUtils.getCellString(billSheet, 1, i);
                if (content == null || StringUtils.isEmpty(content)) {
                    break;
                }
                rowCount++;
            }

            for (int i = 6; i < rowCount + 6; i++) {
                String itemName = ExcelUtils.getCellString(billSheet, 1, i).trim();
                if (itemName == null) {
                    msg = "缺少物料名称！" + itemName;
                    throw new Exception();
                }

                String packDescribe = ExcelUtils.getCellString(billSheet, 2, i);
                if (packDescribe == null) {
                    msg = "缺少单位！" + packDescribe;
                    throw new Exception();
                }

                Double orderQuantity = ExcelUtils.getCellDouble(billSheet, 3, i);
                if (orderQuantity == null) {
                    msg = "缺少订货数量！" + orderQuantity;
                    throw new Exception();
                }
                String memo1 = ExcelUtils.getCellString(billSheet, 4, i);
                String soUdfDs1 = ExcelUtils.getCellString(billSheet, 5, i);
                String soUdfDs2 = ExcelUtils.getCellString(billSheet, 6, i);
                String soUdfDs3 = ExcelUtils.getCellString(billSheet, 7, i);
                ItemInfo itemInfo = itemInfoService.findBy("item_name", itemName);
                PackDetail packDetail = packDetailService.findBy("pack_describe", packDescribe);

                SoDetail soDetail = new SoDetail();

                soDetail.setBillNo(billNo);
                soDetail.setDetailNo(billNo + "-" + (i - 6 + 1));
                soDetail.setItemCode(itemInfo.getItemCode());
                soDetail.setItemName(itemName);
                soDetail.setPackDetailId(packDetail.getPackDetailId());
                soDetail.setPackDescribe(packDescribe);
                soDetail.setOrderQuantity(orderQuantity);
                soDetail.setMemo(memo1);
                soDetail.setSoUdfDs1(soUdfDs1);
                soDetail.setSoUdfDs2(soUdfDs2);
                soDetail.setSoUdfDs3(soUdfDs3);

                soDetailService.save(soDetail);

            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(CommonCode.WRONG_EXCEL_CONTENT, msg);
        } finally {
            billWorkbook.close();
        }

        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "SoMaster导出", notes = "SoMaster导出")
    @GetMapping("/exportSoMaster")
    public Result exportSoMaster(SoMasterCriteria criteria, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        criteria.setPageNum(1);
        criteria.setPageSize(10000);

        List<SoMasterDto> list = soMasterService.findList(criteria);

        String staticPath = fileSetting.getStaticFileDir();
        String downloadPath = "\\download\\SoImport.xls";
        String modelPath = "\\model\\SoImportModel.xls";
        try {
            String modelFilePath = staticPath + modelPath;
            String filePath = staticPath + downloadPath;

            jxl.Workbook workbook = jxl.Workbook.getWorkbook(new java.io.File(modelFilePath));
            WritableWorkbook copy = jxl.Workbook.createWorkbook(new java.io.File(filePath), workbook);

            WritableSheet wSheet = copy.getSheet(0);
            CellFormat format = wSheet.getCell(1, 1).getCellFormat();

            for (int i = 0; i < list.size(); i++) {

                wSheet.insertRow(i + 2);

                SoMaster soMaster = list.get(i);

                String indexStr = Integer.toString(i + 1);
                String billNo = "-";
                if (soMaster.getBillNo() != null) {
                    billNo = soMaster.getBillNo();
                }
                String mergeNo = "-";
                if (soMaster.getMergeNo() != null) {
                    mergeNo = soMaster.getMergeNo();
                }
                String billSource = "-";
                if (soMaster.getBillSource() != null) {
                    billSource = Integer.toString(soMaster.getBillSource());
                }
                String soType = "-";
                if (soMaster.getSoType() != null) {
                    soType = Integer.toString(soMaster.getSoType());
                }
                String organizationName = "-";
                if (soMaster.getOrganizationName() != null) {
                    organizationName = soMaster.getOrganizationName();
                }

                String customerName = "-";
                if (soMaster.getOrganizationName() != null) {
                    customerName = soMaster.getOrganizationName();
                }
                String linkMan = "-";
                if (soMaster.getLinkMan() != null) {
                    linkMan = soMaster.getLinkMan();
                }
                String carrierName = "-";
                if (soMaster.getCarrierName() != null) {
                    carrierName = soMaster.getCarrierName();
                }

                String deliveryTime = "-";
                if (soMaster.getDeliveryTime() != null) {
                    deliveryTime = soMaster.getDeliveryTime();
                }
                String expectTimeFm = "-";
                if (soMaster.getExpectTimeFm() != null) {
                    expectTimeFm = soMaster.getExpectTimeFm();
                }
                String expectTimeTo = "-";
                if (soMaster.getExpectTimeTo() != null) {
                    expectTimeTo = soMaster.getExpectTimeTo();
                }
                String soUdfHs1 = "-";
                if (soMaster.getSoUdfHs1() != null) {
                    soUdfHs1 = soMaster.getSoUdfHs1();
                }
                String soUdfHs2 = "-";
                if (soMaster.getSoUdfHs2() != null) {
                    soUdfHs2 = soMaster.getSoUdfHs2();
                }
                String soUdfHs3 = "-";
                if (soMaster.getSoUdfHs3() != null) {
                    soUdfHs3 = soMaster.getSoUdfHs3();
                }
                String createTime = "-";
                if (soMaster.getCreateTime() != null) {
                    createTime = soMaster.getCreateTime();
                }
                String createUserName = "-";
                if (soMaster.getCreateUserName() != null) {
                    createUserName = soMaster.getCreateUserName();
                }
                String memo = "-";
                if (soMaster.getMemo() != null) {
                    memo = soMaster.getMemo();
                }


                Label indexLabel = new Label(0, i + 2, indexStr);
                Label billNoLabel = new Label(1, i + 2, billNo);
                Label mergeNoLabel = new Label(2, i + 2, mergeNo);
                Label billSourceLabel = new Label(3, i + 2, billSource);
                Label soTypeLabel = new Label(4, i + 2, soType);
                Label organizationNameLabel = new Label(5, i + 2, organizationName);
                Label customerNameLabel = new Label(6, i + 2, customerName);
                Label linkManLabel = new Label(7, i + 2, linkMan);
                Label carrierNameLabel = new Label(8, i + 2, carrierName);
                Label deliveryTimeLabel = new Label(9, i + 2, deliveryTime);
                Label expectTimeFmLabel = new Label(10, i + 2, expectTimeFm);
                Label expectTimeToLabel = new Label(11, i + 2, expectTimeTo);
                Label soUdfHs1Label = new Label(12, i + 2, soUdfHs1);
                Label soUdfHs2Label = new Label(13, i + 2, soUdfHs2);
                Label soUdfHs3Label = new Label(14, i + 2, soUdfHs3);
                Label createTimeLabel = new Label(15, i + 2, createTime);
                Label createUserNameLabel = new Label(16, i + 2, createUserName);
                Label memoLabel = new Label(17, i + 2, memo);

                indexLabel.setCellFormat(format);
                billNoLabel.setCellFormat(format);
                mergeNoLabel.setCellFormat(format);
                billSourceLabel.setCellFormat(format);
                soTypeLabel.setCellFormat(format);
                organizationNameLabel.setCellFormat(format);
                customerNameLabel.setCellFormat(format);
                linkManLabel.setCellFormat(format);
                carrierNameLabel.setCellFormat(format);
                deliveryTimeLabel.setCellFormat(format);
                expectTimeFmLabel.setCellFormat(format);
                expectTimeToLabel.setCellFormat(format);
                soUdfHs1Label.setCellFormat(format);
                soUdfHs2Label.setCellFormat(format);
                soUdfHs3Label.setCellFormat(format);
                createTimeLabel.setCellFormat(format);
                createUserNameLabel.setCellFormat(format);
                memoLabel.setCellFormat(format);

                wSheet.addCell(indexLabel);
                wSheet.addCell(billNoLabel);
                wSheet.addCell(mergeNoLabel);
                wSheet.addCell(billSourceLabel);
                wSheet.addCell(soTypeLabel);
                wSheet.addCell(organizationNameLabel);
                wSheet.addCell(customerNameLabel);
                wSheet.addCell(linkManLabel);
                wSheet.addCell(carrierNameLabel);
                wSheet.addCell(deliveryTimeLabel);
                wSheet.addCell(expectTimeFmLabel);
                wSheet.addCell(expectTimeToLabel);
                wSheet.addCell(soUdfHs1Label);
                wSheet.addCell(soUdfHs2Label);
                wSheet.addCell(soUdfHs3Label);
                wSheet.addCell(createTimeLabel);
                wSheet.addCell(createUserNameLabel);
                wSheet.addCell(memoLabel);
            }


            String nowStr = "打印日期：" + DateUtils.getNowDateString();
            Label dateLabel = new Label(0, list.size() + 3, nowStr);
            dateLabel.setCellFormat(format);
            wSheet.addCell(dateLabel);

            copy.write();
            copy.close();
            workbook.close();

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
        }

        return ResultGenerator.genSuccessResult(downloadPath);
    }


    /**
     * 发送信息到快递鸟下单
     *
     * @param soId
     * @return
     */
    @GetMapping("/sendToKdn")
    public Result sendSoInfoToKdn(Integer soId, Integer tag) {
        if (tag.equals(1)) {


            SoMaster soMaster = soMasterService.getById(soId);
            List<SoDetail> soDetails = soDetailService.findByMasterId(soId);

            EOrderRequestData requestData = new EOrderRequestData();

            List<Commodity> commodities = new ArrayList<>();
            for (SoDetail soDetail : soDetails) {
                Commodity commodity = new Commodity();
                commodity.setGoodsName(soDetail.getItemName());
                commodity.setGoodsCode(soDetail.getItemCode());
                commodity.setGoodsquantity((soDetail.getDeliveryQuantity().intValue()));
                commodity.setGoodsDesc(soDetail.getPackDescribe());
                commodities.add(commodity);
            }

            Carrier carrier = carrierService.getById(soMaster.getCarrierId());
            ReceivingAddress address = receivingAddressService.getById(soMaster.getReceivingAddressId());
            Receiver receiver = new Receiver();
            receiver.setName(address.getLinkMan());
            receiver.setMobile(address.getLinkPhone());
            receiver.setProvinceName(address.getProvince());
            receiver.setCityName(address.getCity());
            receiver.setExpAreaName(address.getArea());
            receiver.setAddress(address.getDetailAddress());

            List<ShippingAddressDto> shippingAddresses = shippingAddressService.findDefaultByOrganizationIdAndWareId(soMaster.getOrganizationId(), soMaster.getWareId());
            if (shippingAddresses.size() == 0) {
                return ResultGenerator.genFailResult(CommonCode.KDN_NO_SHIPPING_ADDRESS);
            }
            ShippingAddress shippingAddress = shippingAddresses.get(0);
            Sender sender = new Sender();
            sender.setName(shippingAddress.getLinkMan());
            sender.setMobile(shippingAddress.getLinkPhone());
            sender.setProvinceName(shippingAddress.getProvince());
            sender.setCityName(shippingAddress.getCity());
            sender.setExpAreaName(shippingAddress.getArea());
            sender.setAddress(shippingAddress.getDetailAddress());

            requestData.setShipperCode(carrier.getCarrierCode());
            requestData.setOrderCode("012657700387");
            requestData.setPayType(1);
            requestData.setExpType("1");
            requestData.setReceiver(receiver);
            requestData.setSender(sender);
            requestData.setQuantity(1);
            requestData.setCommodity(commodities);
            requestData.setIsReturnPrintTemplate("1");
//        requestData.setCustomerName("testyd");
//        requestData.setCustomerPwd("testydpwd");

            String dzmd = kuaidiniaoService.dzmd(requestData);

            JSONObject object = JSONObject.parseObject(dzmd);
            String success = object.getString("Success");
            if ("true".equals(success)) {
                return ResultGenerator.genSuccessResult();
            } else {
                String reason = object.getString("Reason");
                System.out.println(reason);
                return ResultGenerator.genFailResult(CommonCode.KDN_E_ORDER_ERROR);
            }
        } else if (tag.equals(2)) {
            String str = kuaidiniaoService.cloudPrint("SF", "295705773874", 0);
            return ResultGenerator.genSuccessResult(str);
        } else {
            return ResultGenerator.genSuccessResult();
        }
    }

    @GetMapping("/getDeliveryStatus")
    public Result getDeliveryStatus() {
        List<Trace> traces = kuaidiniaoService.jscx("SF", "295705773874");
        return ResultGenerator.genSuccessResult(traces);
    }

    @GetMapping("/getPrintParams")
    public Result getPrintParams(Integer soId, Integer tag, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }
        List<PrintParam> printConfigs = printParamService.findMyConfig(currentUser.getUserId());
        if (printConfigs.size() != 1) {
            return ResultGenerator.genFailResult(CommonCode.KDN_E_ORDER_ERROR, "打印参数错误");
        }
        PrintParam printParam = printConfigs.get(0);
        if (tag.equals(3)) {
            PrintParams printParams = kuaidiniaoService.getCloudPrintParams(printParam.getIp(), printParam.getPrinterName(), "SF", "012657700387", 1);
            List<PrintParams> printParamsList = new ArrayList<>();
            printParamsList.add(printParams);
            return ResultGenerator.genSuccessResult(printParamsList);
        }
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/setCarrier")
    @Transactional
    public Result setCarrier() {
        soMasterService.setCarriersWithRouteTactic();
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/pdaSearchSo")
    public Result pdaSearchSo(String trackCode) {
        List<PdaSearchSoData> dataList = soMasterService.pdaSearchSo(trackCode);
        PageInfo pageInfo = new PageInfo(dataList);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @GetMapping("/getYdypByItemCode")
    @Transactional
    public Result getYdyp(String itemCode, Integer wareId, Integer waveId) {
        SoMasterYdyp soMasterYdyp = soMasterService.getYdyp(itemCode, wareId, waveId);
        if (soMasterYdyp == null) {
            soMasterYdyp = soMasterService.getYdyp2(itemCode, wareId, waveId);
        }

        return ResultGenerator.genSuccessResult(soMasterYdyp);
    }


    @GetMapping("/getSeedingByItemCode")
    @Transactional
    public Result getSeedingByItemCode(String itemCode, Integer wareId, Integer waveMasterId, String cellCode) {
        SoMasterDto soMasterDto = soMasterService.getSeedingByItemCode(itemCode, wareId, waveMasterId);
        SeedingCell seedingCell = seedingCellService.findBy("seeding_cell_code", cellCode);
        if (soMasterDto == null) {
            return ResultGenerator.genSuccessResult();
        }
        seedingCell.setBillNo(soMasterDto.getBillNo());
        seedingCell.setState(0);
        seedingCellService.updateById(seedingCell);
        return ResultGenerator.genSuccessResult(soMasterDto);
    }


    /**
     * 整单发货
     *
     * @param billNo      SO单号
     * @param wareId      仓库ID
     * @param weight      重量
     * @param currentUser 当前用户
     * @return Result
     */
    @GetMapping("/sendOut")
//    @Transactional
    public Result sendOut(String billNo, Integer wareId, Double weight, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER);
        }
        //Step1.判断SO状态是否可以发运
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
        if (ObjectUtil.equal(WareTaskConstant.SO_STATE_OUTED, soMaster.getState())) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该订单"+billNo+"已经发运！");
        }
        //如果没有在工作台被复核 则不允许出库
        if (ObjectUtil.isNotNull(wareId) && ObjectUtil.notEqual(soMaster.getWareId(), wareId)) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "非该仓库发运单！");
        }
        //拣货完毕后才允许发货
        if (soMaster.getState() < WareTaskConstant.SO_STATE_PICKED) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该订单未拣货完毕，不可发运！");
        }

        //如果没有在工作台被复核 则不允许出库
//        if (WareTaskConstant.SO_STATE_OUTED.equals(soMaster.getState())) {
//            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "该订单已发运，不可重复发运！");
//        }

        soMasterService.sendOut(soMaster, currentUser);

        //出库单据回传erp
        String s = soMasterService.outbillToErpNew(billNo);
        if(s == null){
            try {
                throw new Exception("出库回传erp报错");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultGenerator.genSuccessResult();
    }


    @Autowired
    private PrintTempInfoService printTempInfoService;

    @GetMapping("/getDzmd")
    @Transactional
    public Result getDzmd(String billNo) {
        //获取出库单信息
        if (billNo == null || billNo.equals("")) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "单号异常");
        }
        SoMaster soMaster = soMasterService.findBy("bill_no", billNo);
        if (soMaster == null) {
            SeedingCell seedingCell = seedingCellService.findBy("seeding_cell_code", billNo);
            if (seedingCell != null) {
                soMaster = soMasterService.findBy("bill_no", seedingCell.getBillNo());
            }
        }
        if (soMaster == null) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未找到相应订单！");
        }
        List<SoDetail> list = soDetailService.findByBillNo(billNo);
        //获取电子面单模板
        PrintTempInfo printTempInfo = printTempInfoService.findByWareAndShip(soMaster.getWareId(), soMaster.getShipCode());
        if (printTempInfo == null) {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "未找到匹配的电子面单模板");
        }
        String html = printTempInfo.getTempHtml();
        Document doc = Jsoup.parse(html);
        //删除不显示的
        doc.select(".dis-none").remove();
        //直线中间蓝点的问题
        doc.select(".line-handle").remove();
        if (soMaster.getTotalPrice() == null) {
            doc.select(".COD").remove();
            doc.select(".COD_IMG").remove();
        }


        PrintTempUtils.setTempData("SHIP_BILL_NO_BAR_CODE", soMaster.getShipBillCode(), doc, "barCode");
        PrintTempUtils.setTempData("SHIP_BILL_NO_QR_CODE", soMaster.getShipBillCode(), doc, "qrCode");
        PrintTempUtils.setTempData("SHIP_BILL_NO", soMaster.getShipBillCode(), doc, "text");
        PrintTempUtils.setTempData("TRADE_NO", soMaster.getTradeNo(), doc, "text");
        PrintTempUtils.setTempData("SHOP_NAME", soMaster.getShop(), doc, "text");
        PrintTempUtils.setTempData("SENDER_NAME", soMaster.getShipLinkMan(), doc, "text");
        PrintTempUtils.setTempData("SENDER_ADDRESS", soMaster.getShipDetailAddress(), doc, "text");
        PrintTempUtils.setTempData("SENDER_PROVINCE", soMaster.getShipProvince(), doc, "text");
        PrintTempUtils.setTempData("SENDER_CITY", soMaster.getShipCity(), doc, "text");
        PrintTempUtils.setTempData("SENDER_AREA", soMaster.getShipArea(), doc, "text");
        PrintTempUtils.setTempData("SENDER_MOBILE", soMaster.getShipLinkPhone(), doc, "text");
        PrintTempUtils.setTempData("SENDER_COUNTRY", soMaster.getShipCountry(), doc, "text");

        PrintTempUtils.setTempData("RECEIVER_NAME", soMaster.getLinkMan(), doc, "text");
        PrintTempUtils.setTempData("RECEIVER_ADDRESS", soMaster.getDetailAddress(), doc, "text");
        PrintTempUtils.setTempData("RECEIVER_PROVINCE", soMaster.getProvince(), doc, "text");
        PrintTempUtils.setTempData("RECEIVER_CITY", soMaster.getCity(), doc, "text");
        PrintTempUtils.setTempData("RECEIVER_AREA", soMaster.getArea(), doc, "text");
        PrintTempUtils.setTempData("RECEIVER_MOBILE", soMaster.getLinkPhone(), doc, "text");
        PrintTempUtils.setTempData("RECEIVER_COUNTRY", soMaster.getCountry(), doc, "text");

        PrintTempUtils.setTempData("ORDER_TOTAL_PRICE", soMaster.getTotalPrice(), doc, "text");


        PrintTempUtils.setTempData("LMSC", soMaster.getLastMileSortingCode(), doc, "text");
        PrintTempUtils.setTempData("LMD", soMaster.getLastMileDestination(), doc, "text");
        PrintTempUtils.setTempData("LMLC", soMaster.getLastMileLineCode(), doc, "text");
        PrintTempUtils.setTempData("EXT1", soMaster.getSoUdfHs1(), doc, "text");
        PrintTempUtils.setTempData("EXT2", soMaster.getSoUdfHs2(), doc, "text");
        PrintTempUtils.setTempData("EXT3", soMaster.getSoUdfHs3(), doc, "text");

        if (doc.getElementById("FULL_ITEMS_DETAIL_STR") != null) {
            Element parent = doc.getElementById("FULL_ITEMS_DETAIL_STR2");

            Element newEle = parent.getElementById("FULL_ITEMS_DETAIL_STR");
            doc.select("#FULL_ITEMS_DETAIL_STR").remove();
            for (SoDetail soDetail : list) {
                Element newEle2 = newEle.clone();
                PrintTempUtils.setTempData("FULL_ITEMS_DETAIL_STR", soDetail.getItemCode() + "" + soDetail.getItemName() + " * " + soDetail.getOrderQuantity(), newEle2, "text");
                newEle2.appendTo(parent);
            }
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (SoDetail soDetail : list) {
            stringBuilder = stringBuilder.append(soDetail.getItemCode()).append("  ").append(soDetail.getItemName()).append(" X ")
                    .append(soDetail.getOrderQuantity().intValue()).append("; ");
        }
        PrintTempUtils.setTempData("FULL_SKU_STR", stringBuilder.toString(), doc, "text");

        //PrintTempUtils.setTempData("FULL_ITEMS_DETAIL_STR", sb.toString(), doc, "text");

//
//        PrintTempUtils.setTempData("ITEM_CODE_BAR_CODE",acceptRecord.getItemCode(),doc,"barCode");
//        PrintTempUtils.setTempData("ITEM_CODE_QR_CODE",acceptRecord.getItemCode(),doc,"qrCode");

        if (doc.getElementById("ITEM_LIST_DETAIL") != null) {
            Element FULL_ITEMS_DETAIL_TABLE = doc.getElementById("FULL_ITEMS_DETAIL_TABLE");
            Element tbody = FULL_ITEMS_DETAIL_TABLE.getElementsByTag("tBody").get(0);
            Element ITEM_LIST_DETAIL = tbody.getElementById("ITEM_LIST_DETAIL");
            Integer colspan = 0;
            for (SoDetail soDetail : list) {
                Element newEle = ITEM_LIST_DETAIL.clone();
                colspan += PrintTempUtils.setTempData("ITEM_LIST_DETAIL_SKU", soDetail.getItemCode(), newEle, "text");
                colspan += PrintTempUtils.setTempData("ITEM_LIST_DETAIL_NAME_CN", soDetail.getItemName(), newEle, "text");
                colspan += PrintTempUtils.setTempData("ITEM_LIST_DETAIL_QUANTITY", soDetail.getOrderQuantity(), newEle, "text");

                newEle.appendTo(tbody);
            }
            ITEM_LIST_DETAIL.remove();
        }


        //doc在创建时里面包含了html head body等节点  不需要
        Element labelContent = doc.getElementsByAttributeValue("class", "label-content").get(0);
        String tempHtml = labelContent.toString();
        return ResultGenerator.genSuccessResult(tempHtml);
    }

    @ApiOperation(value = "新增先发配件信息", notes = "新增先发配件信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/insert2")
    public Result add2(@RequestBody SoData soData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        soMasterService.createSoMaster2(soData, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/list2")
    public Result list2(SoMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<SoMasterDto> list = soMasterService.findList2(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @ApiOperation(value = "新增原材料信息", notes = "新增原材料信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class, required = true)
    })
    @PostMapping("/insert3")
    public Result add3(@RequestBody SoData soData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        soMasterService.createSoMaster3(soData, currentUser);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/list3")
    public Result list3(SoMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<SoMasterDto> list = soMasterService.findList3(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }


    @GetMapping("alignList")
    public Result alignList(SoMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<SoMasterVo> list = soMasterService.alignList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @PostMapping("submitQitao")
    public Result submitQitao(@RequestBody SoDetailVo soDetailVo) {
        soMasterService.submitQitao(soDetailVo);
        System.out.println(soDetailVo);
        return ResultGenerator.genSuccessResult();

    }

}
